import 'package:auto_size_text/auto_size_text.dart';
import 'package:fedcampus/utility/log.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:table_calendar/table_calendar.dart';

/// 日历选择对话框组件
/// 
/// 提供可视化日期选择界面，支持自定义主题颜色和日期选择回调
class CalendarDialog extends StatefulWidget {
  /// 日期选择变化时的回调函数
  final void Function(DateTime selectedDate) onDateChange;
  
  /// 初始选中的日期
  final DateTime selectedDate;
  
  /// 组件主色调
  final Color primaryColor;
  
  /// 构造函数，初始化必要参数
  const CalendarDialog({
    super.key,
    required this.onDateChange,
    required this.selectedDate,
    required this.primaryColor,
  });

  @override
  State<CalendarDialog> createState() => _CalendarDialogState();
}

class _CalendarDialogState extends State<CalendarDialog> {
  late final ValueNotifier<DateTime> _focusedDay;
  late final ValueNotifier<DateTime> _selectedDay;
  
  // 日期格式化器
  final _dateFormatMonth = DateFormat.yMMMM('zh_CN'); // 中文月份格式
  final _dateFormatDay = DateFormat.d('zh_CN');       // 中文日期格式

  @override
  void initState() {
    super.initState();
    _focusedDay = ValueNotifier(widget.selectedDate);
    _selectedDay = ValueNotifier(widget.selectedDate);
  }

  @override
  void dispose() {
    _focusedDay.dispose();
    _selectedDay.dispose();
    super.dispose();
  }

  /// 日期选择回调处理
  void _onDateSelected(DateTime day, DateTime focusedDay) {
    // 更新选中日期并通知回调
    _selectedDay.value = day;
    widget.onDateChange(day);
    
    // 保持聚焦日期与选中日期一致
    if (!isSameDay(_focusedDay.value, focusedDay)) {
      _focusedDay.value = focusedDay;
    }
  }

  /// 日历页面切换回调
  void _onPageChanged(DateTime day) {
    logger.d('日历页面切换到: ${_dateFormatMonth.format(day)}');
    _focusedDay.value = day;
  }

  @override
  Widget build(BuildContext context) {
    final mediaQuery = MediaQuery.of(context);
    final pixelRatio = mediaQuery.size.width / 360; // 基于360dp宽度的适配比例
    
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        // 月份标题栏
        ValueListenableBuilder<DateTime>(
          valueListenable: _focusedDay,
          builder: (context, value, child) {
            return Container(
              padding: EdgeInsets.symmetric(vertical: 8 * pixelRatio, horizontal: 12 * pixelRatio),
              decoration: BoxDecoration(
                color: widget.primaryColor,
                borderRadius: BorderRadius.circular(8 * pixelRatio),
              ),
              child: Text(
                _dateFormatMonth.format(value),
                style: TextStyle(
                  color: Theme.of(context).colorScheme.onPrimary,
                  fontSize: 16 * pixelRatio,
                  fontWeight: FontWeight.w500,
                ),
              ),
            );
          },
        ),
        
        const SizedBox(height: 12),
        
        // 日历主体
        SizedBox(
          height: 240 * pixelRatio,
          child: TableCalendar(
            // 日历配置
            firstDay: DateTime.utc(2010, 1, 1),
            lastDay: DateTime.utc(2030, 12, 31),
            focusedDay: _focusedDay.value,
            selectedDayPredicate: (day) => isSameDay(_selectedDay.value, day),
            onDaySelected: _onDateSelected,
            onPageChanged: _onPageChanged,
            
            // 日历样式配置
            calendarStyle: CalendarStyle(
              // 工作日样式
              defaultDecoration: _buildDateDecoration(
                bgColor: Theme.of(context).colorScheme.surface,
                textColor: Theme.of(context).colorScheme.onSurface,
              ),
              // 周末样式
              weekendDecoration: _buildDateDecoration(
                bgColor: Theme.of(context).colorScheme.surface,
                textColor: widget.primaryColor,
              ),
              // 今天样式
              todayDecoration: _buildDateDecoration(
                bgColor: Theme.of(context).colorScheme.tertiaryContainer,
                textColor: Theme.of(context).colorScheme.onTertiaryContainer,
              ),
              // 选中日期样式
              selectedDecoration: _buildDateDecoration(
                bgColor: widget.primaryColor,
                textColor: Theme.of(context).colorScheme.onPrimary,
                isSelected: true,
              ),
              
              // 文本样式
              defaultTextStyle: TextStyle(
                fontSize: 14 * pixelRatio,
                fontWeight: FontWeight.normal,
              ),
              weekendTextStyle: TextStyle(
                fontSize: 14 * pixelRatio,
                fontWeight: FontWeight.normal,
                color: widget.primaryColor,
              ),
              selectedTextStyle: TextStyle(
                fontSize: 14 * pixelRatio,
                fontWeight: FontWeight.bold,
              ),
              todayTextStyle: TextStyle(
                fontSize: 14 * pixelRatio,
                fontWeight: FontWeight.bold,
              ),
            ),
            
            // 日历构建器
            calendarBuilders: CalendarBuilders(
              // 星期几标题构建器
              dowBuilder: (context, day) {
                final weekday = day.weekday;
                final text = DateFormat.E('zh_CN').format(day); // 中文星期格式
                
                return Center(
                  child: AutoSizeText(
                    text,
                    style: TextStyle(
                      fontSize: 12 * pixelRatio,
                      fontWeight: FontWeight.w500,
                      color: weekday == DateTime.sunday || weekday == DateTime.saturday
                          ? widget.primaryColor
                          : Theme.of(context).colorScheme.onSurface,
                    ),
                    maxLines: 1,
                  ),
                );
              },
              
              // 日期构建器（可自定义日期显示内容）
              dayBuilder: (context, day, _) {
                return _buildDayWidget(day);
              },
            ),
            
            // 其他配置
            daysOfWeekHeight: 28 * pixelRatio,
            headerVisible: false,
            shouldFillViewport: false,
          ),
        ),
        
        const SizedBox(height: 10),
        
        // 选中日期提示
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '选中日期: ',
              style: TextStyle(
                fontSize: 14 * pixelRatio,
                color: Theme.of(context).colorScheme.onSurface,
              ),
            ),
            Text(
              '${_dateFormatMonth.format(_selectedDay.value)} ${_dateFormatDay.format(_selectedDay.value)}',
              style: TextStyle(
                fontSize: 14 * pixelRatio,
                color: widget.primaryColor,
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建日期单元格装饰
  BoxDecoration _buildDateDecoration({
    required Color bgColor,
    required Color textColor,
    bool isSelected = false,
  }) {
    final pixelRatio = MediaQuery.of(context).size.width / 360;
    final radius = isSelected ? 18 * pixelRatio : 12 * pixelRatio;
    
    return BoxDecoration(
      color: bgColor,
      shape: BoxShape.circle,
      borderRadius: BorderRadius.circular(radius),
    );
  }

  /// 构建日期显示组件
  Widget _buildDayWidget(DateTime day) {
    final isToday = isSameDay(DateTime.now(), day);
    final isSelected = isSameDay(_selectedDay.value, day);
    
    return Container(
      margin: const EdgeInsets.all(2),
      child: Center(
        child: Stack(
          children: [
            // 日期数字
            AutoSizeText(
              day.day.toString(),
              style: TextStyle(
                fontSize: 16 * MediaQuery.of(context).textScaleFactor,
                color: isSelected
                    ? Theme.of(context).colorScheme.onPrimary
                    : day.weekday == DateTime.sunday || day.weekday == DateTime.saturday
                        ? widget.primaryColor
                        : isToday
                            ? Theme.of(context).colorScheme.onTertiaryContainer
                            : Theme.of(context).colorScheme.onSurface,
              ),
              maxLines: 1,
            ),
            
            // 今天标记
            if (isToday && !isSelected)
              Positioned(
                bottom: 2,
                right: 2,
                child: Container(
                  width: 8,
                  height: 8,
                  decoration: BoxDecoration(
                    color: Theme.of(context).colorScheme.tertiary,
                    shape: BoxShape.circle,
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
}